package com.agileai.bpm.controller.define;

import java.util.List;

import org.apache.xmlbeans.XmlException;

import com.agileai.bpm.bizmoduler.define.WfProcessManage;
import com.agileai.bpm.bizmoduler.emulation.WfEmulationManage;
import com.agileai.bpm.bizmoduler.instance.WfProcessInstanceManage;
import com.agileai.bpm.bizmoduler.system.SecurityAuthorizationConfig;
import com.agileai.bpm.controller.emulation.WfEmulationManageListHandler;
import com.agileai.bpm.controller.instance.WfProcessInstanceListHandler;
import com.agileai.bpm.domain.define.Process;
import com.agileai.bpm.model.ProcessDefineDocument;
import com.agileai.bpm.service.define.DefineService;
import com.agileai.bpm.service.running.ProcessEngine;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardListHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.DispatchRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class WfProcessManageListHandler extends StandardListHandler{
	public WfProcessManageListHandler(){
		super();
		this.editHandlerClazz = WfProcessManageEditHandler.class;
		this.serviceId = buildServiceId(WfProcessManage.class);
	}
	
	public ViewRenderer doDesignRequestAction(DataParam param){
		storeParam(param);
		return new DispatchRenderer(getHandlerURL(WfProcessDefineEditHandler.class));
	}
	
	public ViewRenderer doViewInstanceAction(DataParam param){
		return new DispatchRenderer(getHandlerURL(WfProcessInstanceListHandler.class));
	}
	
	public ViewRenderer doUpgradeAction(DataParam param) {
		String processId = param.get("WFP_ID");
		DefineService defineService = (DefineService)this.lookupService("defineService");
		Process process = defineService.loadProcess(processId);
		process.setStatus("unrelease");
		String newVersion = null;
		String version = process.getVersion();
		String prefixTemp = DateUtil.getDateByType(4);
		String prefix = version.substring(0,8);
		if (!prefix.equals(prefixTemp)){
			newVersion = DateUtil.getDateByType(4)+"_01";
		}else{
			String postfix = version.substring(9);
			int postfixNum = Integer.parseInt(postfix);
			String posFix = "0"+String.valueOf(postfixNum+1);
			newVersion = prefix + "_" + posFix.substring(posFix.length()-2,posFix.length());	
		}
		User user = (User)this.getUser();
		process.setVersion(newVersion);
		process.setCreateTime(DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL));
		process.setCreaterId(user.getUserId());
		process.setModifier(user.getUserId());
		process.setModifyTime(DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL));
		defineService.createProcess(process);
		String newProcId = process.getId();
		return new AjaxRenderer(newProcId);
	}
	public ViewRenderer doCopyRequestAction(DataParam param){
		String rspText = "";
		String processId = param.get("WFP_ID");
		String processCode = param.get("WFP_CODE");
		WfProcessManage wfProcessManage = (WfProcessManage)this.lookupService(WfProcessManage.class);
		DataParam dataParam = new DataParam();
		dataParam.put("WFP_CODE",processCode);
		List<DataRow> records = wfProcessManage.findRecords(dataParam);
		if (!ListUtil.isNullOrEmpty(records)){
			rspText = "exist";
		}else{
			DefineService defineService = (DefineService)this.lookupService("defineService");
			Process process = defineService.loadProcess(processId);
			process.setStatus("unrelease");
			String version = DateUtil.getDateByType(4)+"_01";
			User user = (User)this.getUser();
			process.setCreateTime(DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL));
			process.setCreaterId(user.getUserId());
			process.setModifier(user.getUserId());
			process.setModifyTime(DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL));
			process.setVersion(version);
			process.setCode(processCode);
			
			String processDefineXML = process.getDefineXML();
			try {
				ProcessDefineDocument processDefineDocument = ProcessDefineDocument.Factory.parse(processDefineXML);
				processDefineDocument.getProcessDefine().setCode(processCode);
				process.setDefineXML(processDefineDocument.toString());
			} catch (XmlException e) {
				e.printStackTrace();
			}
			defineService.createProcess(process);
			rspText = process.getId();
		}
		return new AjaxRenderer(rspText);
	}	
	
	public ViewRenderer doPublishCancelAction(DataParam param){
		String rspText = "";
		try {
			String wfpState = param.get("CUR_WFP_STATE");
			WfProcessManage service = (WfProcessManage)this.lookupService(WfProcessManage.class);
			DataRow record = service.getRecord(param);
			String version = record.getString("WFP_VERSION");
			DataParam newParam = record.toDataParam(true);
			if ("released".equals(wfpState)){
				newParam.put("WFP_STATE","unrelease");
			}
			else{
				newParam.put("WFP_STATE","released");
				if (StringUtil.isNullOrEmpty(version)){
					newParam.put("WFP_VERSION",DateUtil.getDateByType(4)+"_1");
				}
				String processId = param.get("WFP_ID");
				ProcessEngine engine = (ProcessEngine)this.lookupService("processEngine");
				Process process = engine.retrieveProcess(processId);
				engine.registryProcess(processId, process);
			}
			service.updateRecord(newParam);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		rspText = SUCCESS;
		return new AjaxRenderer(rspText);
	}
	
	@PageAction
	public ViewRenderer reloadProcess(DataParam param){
		String rspText = "";
		try {
			String processId = param.get("WFP_ID");
			ProcessEngine engine = (ProcessEngine)this.lookupService("processEngine");
			Process process = engine.retrieveProcess(processId);
			engine.registryProcess(processId, process);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		rspText = SUCCESS;
		return new AjaxRenderer(rspText);
	}
	
	public ViewRenderer doViewEmulationAction(DataParam param){
		return new DispatchRenderer(this.getHandlerURL(WfEmulationManageListHandler.class));
	}
	protected void processPageAttributes(DataParam param) {
		FormSelect typeGroupFormSelect = FormSelectFactory.create("WF_GROUP");
		String wfGroup = getAttributeValue("WFP_GROUP");
		typeGroupFormSelect.setSelectedValue(wfGroup);
		this.setAttribute("WFP_GROUP", typeGroupFormSelect);
		FormSelect stateSelect = FormSelectFactory.create("WF_STATE");
		String wfState = getAttributeValue("WFP_STATE");
		stateSelect.setSelectedValue(wfState);
		this.setAttribute("WFP_STATE", stateSelect);
		
		this.initMappingItem("WFP_STATE", stateSelect.getContent());
		this.initMappingItem("WFP_GROUP", typeGroupFormSelect.getContent());
	}
	public ViewRenderer doCheckExistAction(DataParam param){
		String rspText = "";
		WfEmulationManage wfEmulationManage = (WfEmulationManage)this.lookupService(WfEmulationManage.class);
		List<DataRow> records = wfEmulationManage.findRecords(param);
		if (!ListUtil.isNullOrEmpty(records)){
			rspText = "ExistEmulation";
		}else{
			WfProcessInstanceManage wfProcessInstanceManage = (WfProcessInstanceManage)this.lookupService(WfProcessInstanceManage.class);
			int instanceNumber = wfProcessInstanceManage.queryInstanceNumber(param); 
			if (instanceNumber > 0){
				rspText = "ExistInstance";
			}
		}
		return new AjaxRenderer(rspText);
	}
	public ViewRenderer doDeleteAction(DataParam param){
		storeParam(param);
		String processId = param.get("WFP_ID"); 

		SecurityAuthorizationConfig securityAuthorizationConfig = (SecurityAuthorizationConfig)this.lookupService("securityAuthorizationConfigService");
		securityAuthorizationConfig.delUserAuthRelations("Process", processId);
		securityAuthorizationConfig.delRoleAuthRelations("Process", processId);
		securityAuthorizationConfig.delGroupAuthRelations("Process", processId);
		
		DefineService defineService = (DefineService)this.lookupService("defineService");
		defineService.deleteProcess(processId);
		
		return new RedirectRenderer(getHandlerURL(getClass()));
	}

	protected void initParameters(DataParam param) {
		param.remove("WFP_CODE");
	}
	protected WfProcessManage getService() {
		return (WfProcessManage)this.lookupService(this.getServiceId());
	}
}
